package com.youlai.boot.system.converter;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.format.Formatter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

@Configurable
public class WebMvcConfig implements WebMvcConfigurer {



    public void  addFormatters(FormatterRegistry registry){
        registry.addFormatter((Formatter<?>) new DateTimeFormatterRegistrar());
    }

    private static class DateTimeFormatterConverter implements Formatter<LocalDateTime> {

        private final DateTimeFormatter dateTimeFormatter;

        private DateTimeFormatterConverter(DateTimeFormatter dateTimeFormatter) {
            this.dateTimeFormatter = dateTimeFormatter;
        }


        @Override
        public LocalDateTime parse(String text, Locale locale) throws ParseException {
            return LocalDateTime.parse(text, dateTimeFormatter);
        }

        @Override
        public String print(LocalDateTime object, Locale locale) {
            return dateTimeFormatter.format(object);
        }
    }
}
